package com.beaven.model.net;

import android.text.TextUtils;
import com.beaven.model.Factory;
import com.beaven.model.model.sp.Account;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * author: Beaven
 * time: 2017/5/18 10:41
 *
 * 网络请求设定
 */

public class NetFactory {
  private static Retrofit retrofit;

  public static final String API_URL = "http://10.134.10.2:8080/api/";
  public static final String API_URL_ONE = "http://192.168.1.3:8080/api/";

  public static HTTPService getService() {
    return NetFactory.getRetrofit().create(HTTPService.class);
  }

  private static Retrofit getRetrofit() {
    if (retrofit != null) {
      return retrofit;
    }
    // OkHttp
    OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() {
      @Override public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();
        if (!TextUtils.isEmpty(Account.getToken())) {
          // 添加token请求头
          builder.addHeader("token", Account.getToken());
        }
        builder.addHeader("Content-Type", "application/json");
        Request newRequest = builder.build();
        return chain.proceed(newRequest);
      }
    })
        .addNetworkInterceptor(new StethoInterceptor())
        .readTimeout(3, TimeUnit.SECONDS)
        .connectTimeout(3, TimeUnit.SECONDS)
        .build();
    // Retrofit
    retrofit = new Retrofit.Builder().client(client)
        .baseUrl(API_URL)
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(Factory.getGson()))
        .build();
    return retrofit;
  }
}
